package cn.csc.module.order.service.shopcart;

import cn.csc.framework.common.pojo.PageResult;
import cn.csc.module.order.controller.app.shopcart.vo.*;
import cn.csc.module.order.convert.shopcart.ShopCartItemConvert;
import cn.csc.module.order.dal.dataobject.shopcart.ShopCartItemDO;
import cn.csc.module.order.dal.mysql.shopcart.ShopCartItemMapper;
import cn.csc.module.product.api.spu.SpuApi;
import cn.csc.module.product.api.spu.dto.SpuDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import static cn.csc.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.csc.module.order.enums.ErrorCodeConstants.SHOP_CART_ITEM_NOT_EXISTS;

/**
 * 购物车 Service 实现类
 *
 * @author liuchuang
 */
@Service
@Validated
public class ShopCartItemServiceImpl implements ShopCartItemService {

    @Resource
    private ShopCartItemMapper shopCartItemMapper;
    @Resource
    private SpuApi spuApi;
    @Override
    public Long createShopCartItem(AppShopCartItemCreateReqVO createReqVO) {
        // 插入
        ShopCartItemDO shopCartItem = ShopCartItemConvert.INSTANCE.convert(createReqVO);
        shopCartItemMapper.insert(shopCartItem);
        // 返回
        return shopCartItem.getId();
    }

    @Override
    public void updateShopCartItem(AppShopCartItemUpdateReqVO updateReqVO) {
        // 校验存在
        validateShopCartItemExists(updateReqVO.getId());
        // 更新
        shopCartItemMapper.updateById(ShopCartItemConvert.INSTANCE.convert(updateReqVO));
    }

    @Override
    public void deleteShopCartItem(Long id) {
        // 校验存在
        validateShopCartItemExists(id);
        // 删除
        shopCartItemMapper.deleteById(id);
    }

    private void validateShopCartItemExists(Long id) {
        if (shopCartItemMapper.selectById(id) == null) {
            throw exception(SHOP_CART_ITEM_NOT_EXISTS);
        }
    }

    @Override
    public ShopCartItemDO getShopCartItem(Long id) {
        return shopCartItemMapper.selectById(id);
    }

    @Override
    public List<ShopCartItemDO> getShopCartItemList(Collection<Long> ids) {
        return shopCartItemMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<ShopCartItemDO> getShopCartItemPage(AppShopCartItemPageReqVO pageReqVO) {
        return shopCartItemMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ShopCartItemDO> getShopCartItemList(AppShopCartItemExportReqVO exportReqVO) {
        return shopCartItemMapper.selectList(exportReqVO);
    }

    @Override
    public List<ShopCartItemDO> getShopCartItemList(BigInteger userId) {
        return shopCartItemMapper.getShopCartItemList(userId);
    }

    @Override
    public List<ShopCartItemDO> selectShopIdList(BigInteger userId, BigInteger shopId) {
        return shopCartItemMapper.selectShopIdList(userId,shopId);
    }

    @Override
    public ShopCartItemDO getShopCartItem(AppShopCartItemBaseVO reqVo) {
        QueryWrapper queryWrapper= new QueryWrapper();
        queryWrapper.eq("sku_id",reqVo.getSkuId());
        queryWrapper.eq("spu_id",reqVo.getSpuId());
        queryWrapper.eq("user_id",reqVo.getUserId());
        queryWrapper.eq("shop_id",reqVo.getShopId());
        queryWrapper.eq("deleted",0);
        return shopCartItemMapper.selectOne(queryWrapper);
    }



    @Override
    public void updateBatchOfDeleted(List<Long> ids) {
        for(Long id:ids){
            ShopCartItemDO shopCartItemDO= new ShopCartItemDO();
            shopCartItemDO.setId(id);
            shopCartItemDO.setDeleted(true);
            shopCartItemMapper.updateById(shopCartItemDO);
        }
    }

    @Override
    public Long selectNumByUserId(BigInteger userId) {
        QueryWrapper<ShopCartItemDO> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("deleted",0);
        List<ShopCartItemDO> list = shopCartItemMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(list)){
            return 0L;
        }
        //判断商品是否下架
        List<BigInteger> spuIds = spuApi.getSpuList(list.stream().map(ShopCartItemDO::getSpuId).collect(Collectors.toList())).getCheckedData()
                .stream().filter(c-> c.getVerifyStatus()!=10).collect(Collectors.toList())
                .stream().map(SpuDTO::getId).collect(Collectors.toList());
        List<ShopCartItemDO> filterList = list.stream().filter(e -> !spuIds.contains(e.getSpuId())).collect(Collectors.toList());
        return filterList.isEmpty() ? 0L : filterList.stream().map(ShopCartItemDO::getCount).reduce(Integer::sum).get().longValue() ;
    }

    @Override
    public void updateBatchByOrderId(List<Long> ids, BigInteger orderId) {
        UpdateWrapper updateWrapper = new UpdateWrapper();//清掉原打标的数据
        updateWrapper.set("order_id",orderId);
        updateWrapper.eq("order_id",orderId);
        shopCartItemMapper.update(new ShopCartItemDO(),updateWrapper);
          for(Long id:ids){//重新给数据标记订单id
              ShopCartItemDO shopCartItemDO= new ShopCartItemDO();
              shopCartItemDO.setId(id);
              shopCartItemDO.setOrderId(orderId);
              shopCartItemMapper.updateById(shopCartItemDO);
          }
    }

    @Override
    public List<Long> getShopCartItemIds(BigInteger orderId) {
        return shopCartItemMapper.getShopCartItemIds(orderId);
    }

    @Override
    public void updateShopCartItem(ShopCartItemDO shopCartItemDO) {
        // 校验存在
        validateShopCartItemExists(shopCartItemDO.getId());
        shopCartItemMapper.updateById(shopCartItemDO);
    }

    @Override
    public void deleteShopCartItemByOrderId(List<BigInteger> orderIds) {
        shopCartItemMapper.deleteShopCartItemByOrderId(orderIds);
    }

    @Override
    public List<ShopCartItemDO> selectShopIdsList(BigInteger userId, List<BigInteger> shopIds) {
        return shopCartItemMapper.selectShopIdsList(userId,shopIds);
    }
}
